package com.shouer.doc.ui.healthreportedit;

import android.content.Context;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.shouer.doc.R;
import com.shouer.doc.application.App;
import com.shouer.doc.common.util.AppUtil;
import com.shouer.doc.common.util.DateFormatUtil;
import com.shouer.doc.common.util.ScreenUtils;
import com.shouer.doc.dialog.CommonDialogUtil;
import com.shouer.doc.dialog.ShouerLoadingDialogUtil;
import com.shouer.doc.ui.healthreportedit.adapter.StuffRemarkAdapter;
import com.shouer.doc.ui.healthreportedit.adapter.UserRemarkAdapter;
import com.shouer.doc.ui.healthreportedit.presenter.HealthReportEditPresenterImpl;
import com.shouer.doc.ui.healthreportedit.presenter.IHealthReportEditPresenter;
import com.shouer.doc.ui.healthreportedit.view.HealthReportEditView;
import com.shouer.doc.ui.login.model.DoctorInfoModel;
import com.shouer.doc.ui.login.model.UserModel;
import com.shouer.doc.ui.neworder.adapter.HealthRecordAdapter;
import com.shouer.doc.ui.neworder.model.HealthRecord;
import com.shouer.doc.ui.neworder.model.StuffRemark;
import com.shouer.doc.widget.ShouerLayoutManager;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by YYY-Work on 2017/7/27.
 */

public class HealthReportEditActivity extends AppCompatActivity implements HealthReportEditView,View.OnClickListener{


    @BindView(R.id.tab1)
    protected View tab1;
    @BindView(R.id.tab2)
    protected View tab2;

    @BindView(R.id.navigation_view)
    protected ImageView navigationView;
    private Animation animation;
    private int offset,one;

    @BindView(R.id.detail_layout)
    protected View detailView;
    @BindView(R.id.bottom_layout)
    protected View bottomLayout;
    @BindView(R.id.question_list)
    protected XRecyclerView questionList;
    @BindView(R.id.stuff_remark_layout)
    protected View stuffRemarkLayout;

    @BindView(R.id.stuff_remark_list)
    protected RecyclerView stuffRemarkList;
    @BindView(R.id.advice_layout)
    protected View adviceLayout;

    @BindView(R.id.advice_list)
    protected LinearLayout adviceList;
    @BindView(R.id.add)
    protected View addView;
    @BindView(R.id.action_layout)
    protected View actionLayout;

    @BindView(R.id.ok_btn)
    protected View okBtn;
    @BindView(R.id.save_btn)
    protected View saveBtn;

    private App app;
    private String recId;

    private IHealthReportEditPresenter presenter;
    private HealthRecord record;


    @Override
    public void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        setContentView(R.layout.activity_health_report_edit_activity);
        ButterKnife.bind(this);

        recId=getIntent().getStringExtra("recId");
        if (TextUtils.isEmpty(recId))
        {
            finish();
        }

        app= (App) getApplicationContext();
        presenter=new HealthReportEditPresenterImpl(this);


        ShouerLayoutManager layoutManager=new ShouerLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        questionList.setLayoutManager(layoutManager);
        questionList.setLoadingMoreEnabled(false);
        questionList.setPullRefreshEnabled(false);

        ShouerLayoutManager layoutManager2=new ShouerLayoutManager(this);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        stuffRemarkList.setLayoutManager(layoutManager2);

        tab1.setSelected(true);
        int imgWidth = (int) getResources().getDimension(R.dimen.navigation_img_width_2);
        offset = (ScreenUtils.getScreenWidth(this)/2 - imgWidth) / 2;
        one = ScreenUtils.getScreenWidth(this)/2;
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        navigationView.setImageMatrix(matrix);// 设置动画初始位置

        ShouerLoadingDialogUtil.getInstance().show(this);
        presenter.queryHealthRecordDetail(recId);
    }

    @OnClick(value = {R.id.add,R.id.title_left,R.id.tab1,R.id.tab2,R.id.save_btn,R.id.ok_btn})
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.title_left:
                finish();
                break;
            case R.id.add:
                if (adviceList.getChildCount()<10)
                {
                    addAdvice(null);
                }
                break;
            case R.id.tab1:
                if (questionList.getVisibility()!=View.VISIBLE)
                {
                    tab2.setSelected(false);
                    tab1.setSelected(true);
                    setSelectedForDirectiveImg(0);
                    stuffRemarkLayout.setVisibility(View.GONE);
                    addView.setVisibility(View.GONE);
                    questionList.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tab2:
                if (stuffRemarkLayout.getVisibility()!=View.VISIBLE)
                {
                    tab1.setSelected(false);
                    tab2.setSelected(true);
                    setSelectedForDirectiveImg(1);
                    questionList.setVisibility(View.GONE);
                    if (record.getOperFlag()==3)
                    {
                        addView.setVisibility(View.VISIBLE);
                    }
                    stuffRemarkLayout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.save_btn:
                buttonaction(0);
                break;
            case R.id.ok_btn:
                CommonDialogUtil.getInstance().showMessage(this,this,"确定提交健康报告吗？","取消","提交");
                break;
            case R.id.dialog_left_btn:
                CommonDialogUtil.getInstance().dismiss();
                break;
            case R.id.dialog_right_btn:
                CommonDialogUtil.getInstance().dismiss();
                buttonaction(1);
                break;

        }

    }

    @Override
    public void onDestroy()
    {
        presenter.onDestroy();
        super.onDestroy();
    }


    private void buttonaction(int type)
    {
        saveBtn.setClickable(false);
        okBtn.setClickable(false);
        StringBuffer subTitle=new StringBuffer();
        StringBuffer subDesc=new StringBuffer();
        StringBuffer defaultTags=new StringBuffer();
        int childCount=adviceList.getChildCount();
        for (int i=0;i<childCount;i++)
        {
            View childView=adviceList.getChildAt(i);
            EditText titleInput= (EditText) childView.findViewWithTag("titleTag");
            EditText contentInput= (EditText) childView.findViewWithTag("contentTag");
            TextView defaultTagView= (TextView) childView.findViewWithTag("defaultTag");
            if (null!=titleInput&&null!=contentInput)
            {
                String title=titleInput.getText().toString().trim();
                String content=contentInput.getText().toString().trim();
                String defaultTag=defaultTagView.getText().toString().trim();

                title= TextUtils.isEmpty(title)?"":title;
                content= TextUtils.isEmpty(content)?"":content;

//                if (!TextUtils.isEmpty(title)&&!TextUtils.isEmpty(content))
//                {
                    subTitle.append(title).append("#");
                    subDesc.append(content).append("#");
                    defaultTags.append(defaultTag).append("#");
//                }

            }
        }
        if (!TextUtils.isEmpty(subTitle)&&!TextUtils.isEmpty(subDesc))
        {
            String titleString=subTitle.toString();
            String descString=subDesc.toString();
            String defaultTagsString=defaultTags.toString();
            titleString=titleString.substring(0,titleString.length()-1);
            descString=descString.substring(0,descString.length()-1);
            defaultTagsString=defaultTagsString.substring(0,defaultTagsString.length()-1);
            presenter.saveHealthRecord(recId,titleString,descString,defaultTagsString,type);
        }else
        {
            saveBtn.setClickable(true);
            okBtn.setClickable(true);
        }
    }

    private void setSelectedForDirectiveImg(int position) {

        if (position == 0) {
            animation = new TranslateAnimation(one, 0, 0, 0);
        } else {
            animation = new TranslateAnimation(0, one, 0, 0);
        }
        animation.setFillAfter(true);// True:图片停在动画结束位置
        animation.setDuration(300);
        navigationView.startAnimation(animation);

    }

    View.OnClickListener delBtnListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (adviceList.getChildCount()>1)
            {
                String parentTag= (String) v.getTag(R.id.list_position);
                View parentView=adviceList.findViewWithTag(parentTag);
                if (null!=parentView)
                {
                    adviceList.removeView(parentView);
                }
            }

        }
    };

    private void addAdvice(StuffRemark stuffRemark)
    {
        long tag=0;
        if(adviceList.getChildCount()==0)
        {
            tag=1;
        }else
        {
            View lastView=adviceList.getChildAt(adviceList.getChildCount()-1);
            String lastTag= (String) lastView.getTag();
            tag=Long.valueOf(lastTag.split("-")[1])+1;
        }
        View adviceView= LayoutInflater.from(this).inflate(R.layout.activity_health_report_edit_part,null);
        View delView=adviceView.findViewWithTag("del_tag");
        EditText titleInput= (EditText) adviceView.findViewWithTag("titleTag");
        EditText contentInput= (EditText) adviceView.findViewWithTag("contentTag");
        TextView defaultTagView= (TextView) adviceView.findViewWithTag("defaultTag");
        TextView unEditTitleView= (TextView) adviceView.findViewWithTag("titleTagUnEdit");
        if (null!=delView)
        {
            adviceView.setTag("parent-"+tag);
            delView.setTag(R.id.list_position,"parent-"+tag);
            delView.setOnClickListener(delBtnListener);

            if (record.getOperFlag()==3)
            {
                delView.setClickable(true);
            }else
            {
                delView.setVisibility(View.INVISIBLE);
                delView.setClickable(false);
            }

            if (null!=stuffRemark&&stuffRemark.getDefaultFlag()==1)
            {
                delView.setVisibility(View.INVISIBLE);
                delView.setClickable(false);
            }
        }

        if (null!=titleInput)
        {

            if (record.getOperFlag()==3)
            {
                titleInput.setEnabled(true);
            }else
            {
                titleInput.setEnabled(false);
            }

            if (null!=stuffRemark)
            {
                titleInput.setText(TextUtils.isEmpty(stuffRemark.getSubTitle())?"":stuffRemark.getSubTitle());
                unEditTitleView.setText(TextUtils.isEmpty(stuffRemark.getSubTitle())?"":stuffRemark.getSubTitle());
                if (stuffRemark.getDefaultFlag()==1)
                {
//                    titleInput.setEnabled(false);
//                    titleInput.setBackgroundResource(R.drawable.translate_bg);
                    titleInput.setVisibility(View.GONE);
                    unEditTitleView.setVisibility(View.VISIBLE);

                }else
                {
                    unEditTitleView.setVisibility(View.GONE);
                    titleInput.setVisibility(View.VISIBLE);

                }
            }
        }

        if (null!=contentInput)
        {

            if (record.getOperFlag()==3)
            {
                contentInput.setEnabled(true);
            }else
            {
                contentInput.setEnabled(false);
            }


            if (null!=stuffRemark)
            {
                contentInput.setText(TextUtils.isEmpty(stuffRemark.getSubDesc())?"":stuffRemark.getSubDesc());
            }
        }

        if (null!=defaultTagView)
        {
            if (null!=stuffRemark)
            {
                defaultTagView.setText(String.valueOf(stuffRemark.getDefaultFlag()));
            }
        }

        adviceList.addView(adviceView);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public UserModel getUser() {
        return app.getUserModel();
    }

    public DoctorInfoModel getUserDocInfo()
    {
        return app.getUserDocInfo();
    }

    @Override
    public void queryHealthRecordSuccess(HealthRecord record) {
        this.record=record;
        if ((record.getOperFlag()==3||record.getOperFlag()==4||record.getOperFlag()==5)&&app.getUserDocInfo().getDocId().equals(record.getAccepterId()))
        {

            if (record.getOperFlag()==3)
            {
                actionLayout.setVisibility(View.VISIBLE);
                addView.setClickable(true);
            }else
            {
                actionLayout.setVisibility(View.GONE);
                addView.setClickable(false);
            }

            View headView=LayoutInflater.from(this).inflate(R.layout.activity_health_report_edit_head,null);
            SimpleDraweeView patientIco= (SimpleDraweeView) headView.findViewById(R.id.ico);
            TextView patNameView= (TextView) headView.findViewById(R.id.name);
            TextView patSexView= (TextView) headView.findViewById(R.id.sex);
            TextView patDataView= (TextView) headView.findViewById(R.id.date);

            if (record.getPatient().getPatSex()==0)
            {
                String icoUriString="res://"+ AppUtil.getPackageName(this)+"/"+R.drawable.ico_paitent_girl;
                Uri uri=Uri.parse(icoUriString);
                patientIco.setImageURI(uri);
            }else
            {
                String icoUriString="res://"+ AppUtil.getPackageName(this)+"/"+R.drawable.ico_paitent_boy;
                Uri uri=Uri.parse(icoUriString);
                patientIco.setImageURI(uri);
            }

            patNameView.setText(TextUtils.isEmpty(record.getPatient().getPatName())?"":record.getPatient().getPatName());
            patSexView.setText(record.getPatient().getPatSex()==0?"女":"男");
            try {
                Date createDate= DateFormatUtil.stringToDate(record.getPatient().getPatBirthday().replace("T","\b"),"yyyy-MM-dd\bHH:mm:ss");
                patDataView.setText(DateFormatUtil.dateToString(createDate,"yyyy-MM-dd"));
            } catch (Exception e) {
                Log.d(HealthRecordAdapter.class.getSimpleName(), e.toString());
                patDataView.setText("");
            }

            questionList.addHeaderView(headView);
            UserRemarkAdapter remarkAdapter=new UserRemarkAdapter(this,record.getRemarkList());
            questionList.setAdapter(remarkAdapter);

            if (record.getOperFlag()==3)
            {
                if (null!=record.getDocRemarkList()&&record.getDocRemarkList().size()>0)
                {
                    for (StuffRemark stuffRemark:record.getDocRemarkList())
                    {
                        addAdvice(stuffRemark);
                    }
                }else
                {
                    addAdvice(null);
                }

                adviceLayout.setVisibility(View.VISIBLE);
                stuffRemarkList.setVisibility(View.GONE);

            }else {
                StuffRemarkAdapter stuffRemarkAdapter=new StuffRemarkAdapter(this,record.getDocRemarkList());
                stuffRemarkList.setAdapter(stuffRemarkAdapter);

                adviceLayout.setVisibility(View.GONE);
                stuffRemarkList.setVisibility(View.VISIBLE);
            }

            bottomLayout.setVisibility(View.VISIBLE);
            questionList.setVisibility(View.VISIBLE);


        }else
        {
            Toast.makeText(this,"健康档案状态异常",Toast.LENGTH_SHORT).show();
        }

        ShouerLoadingDialogUtil.getInstance().dismiss();
    }

    @Override
    public void queryHealthRecordFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(this,failInfo,Toast.LENGTH_SHORT).show();

    }

    @Override
    public void saveHealthRecordSuccess(int type) {
        if (type==0)
        {
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
            saveBtn.setClickable(true);
            okBtn.setClickable(true);
        }else
        {
            presenter.submitHealthRecord(recId);
        }
    }

    @Override
    public void saveHealthRecordFailed(String failInfo) {

        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(this,failInfo,Toast.LENGTH_SHORT).show();
        saveBtn.setClickable(true);
        okBtn.setClickable(true);

    }

    @Override
    public void submitHealthRecordSuccess() {
        Toast.makeText(this,"提交成功",Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void submitHealthRecordFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        Toast.makeText(this,failInfo,Toast.LENGTH_SHORT).show();
        saveBtn.setClickable(true);
        okBtn.setClickable(true);
    }
}
